package com.qs.controller;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qs.controller.dto.LoginDTO;
import com.qs.controller.dto.ProfileDTO;
import com.qs.controller.dto.UserDTO;
import com.qs.controller.vo.UserVO;
import com.qs.mapper.entity.User;
import com.qs.service.UserService;
import com.qs.service.bo.UserBO;
import com.qs.util.BeanCopyUtils;
import com.qs.util.R;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;


@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final StpInterface stpInterface;

    @PostMapping("/login")
    public SaResult login(@RequestBody UserVO userVO) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(User::getUsername, userVO.getUsername());
        lambdaQueryWrapper.eq(User::getPassword, userVO.getPassword());
        User user = userService.getOne(lambdaQueryWrapper);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        StpUtil.login(user.getUsername());
        Long expires = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() + StpUtil.getTokenTimeout() * 1000;
        String token = StpUtil.getTokenValue();
        return SaResult.data(new LoginDTO(token, expires));
    }

    @GetMapping("/logout")
    public R<String> logout() {
        StpUtil.logout();
        return R.ok();
    }

    @GetMapping("/profile")
    public R<ProfileDTO> profile() {
        String userName = (String) StpUtil.getLoginId();
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(User::getUsername, userName);
        // 查询用户信息
        User user = userService.getOne(lambdaQueryWrapper);
        // 查询权限信息
        List<String> permissionList = stpInterface.getPermissionList(user.getId(), StpUtil.getLoginType());
        List<String> roleList = stpInterface.getRoleList(user.getUsername(), StpUtil.getLoginType());
        // 查询角色信息
        return R.ok(ProfileDTO.builder()
                .account(BeanCopyUtils.copyBean(user, UserDTO.class))
                // 暂时不加权限，使用角色作为权限
                .permissions(roleList)
                .role(roleList)
                .build());
    }

    @GetMapping
    private R<List<UserBO>> list() {
        List<User> userList = userService.list();
        List<UserBO> userBOList = BeanCopyUtils.copyBeanList(userList, UserBO.class);
        return R.ok(userBOList);
    }

    @GetMapping("/page")
    private R<Page<UserBO>> queryByPage(@RequestParam("username") String username, @RequestParam("current") Long current, @RequestParam("size") Long size) {
        Page<User> page = new Page<>(current, size);
        Page<UserBO> result = userService.queryByPage(username, page);
        return R.ok(result);
    }

    @PostMapping
    private R<String> add(@RequestBody UserVO userVO) {
        UserBO userBO = BeanCopyUtils.copyBean(userVO, UserBO.class);
        String result = userService.add(userBO);
        return R.ok(result);
    }

    @PutMapping
    private R<String> edit(@RequestBody UserVO userVO) {
        UserBO userBO = BeanCopyUtils.copyBean(userVO, UserBO.class);
        String result = userService.edit(userBO);
        return R.ok(result);
    }

    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable("id") Long id) {
        boolean removed = userService.removeById(id);
        return R.ok(removed);
    }
}
